package br.unesp.rc.rafaelt.client;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * WS Client.
 *
 */
public class WSClient {

    /**
     * The main method.
     *
     * @param args the arguments
     * @throws Exception the exception
     */
    public static void main(String[] args) throws Exception {

        //String request = "http://localhost:8080/spring-rest/rest/author/all.json";
    	String request = "http://localhost:8080/json-rest-server-v2/authors";

        System.out.println(request);

        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(request);

        // Send GET request
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        } else {
            InputStream rstream = null;

            // Get the response body
            rstream = method.getResponseBodyAsStream();

            // Process the response from Web Service
            parseJSON(rstream);
        }


    }

    /**
     * Parses the json.
     *
     * @param rstream the rstream
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private static void parseJSON(InputStream rstream) throws IOException {    	
    	ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    	AuthorWrapper authorList = mapper.readValue(rstream, AuthorWrapper.class);
    	
    	for (Author author : authorList.getAuthorList()){
    		System.out.println(author.getId() + "\t" + author.getName());
    	}
    	
    }
}
